﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AndroidTools
{
    class Helper
    {

        public static string Cmd(string command,bool isThread=false)
        {
            CmdRes res = new CmdRes() { Command = command };
            if (isThread)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(CmdExec));
                thread.Start(res);
            }
            else
            {
                CmdExec(res);

            }

            return res.Result;
        }


        private static void CmdExec(object obj)
        {
            CmdRes cmdRes = (CmdRes)obj;

            string command = cmdRes.Command;
            string outStr = "";

            using (Process pc = new Process())
            {
                command = command.Trim().TrimEnd('&') + "&exit";

                pc.StartInfo.FileName = "cmd.exe";
                pc.StartInfo.CreateNoWindow = true;
                pc.StartInfo.RedirectStandardError = true;
                pc.StartInfo.RedirectStandardInput = true;
                pc.StartInfo.RedirectStandardOutput = true;
                pc.StartInfo.UseShellExecute = false;

                pc.Start();

                pc.StandardInput.WriteLine(command);
                pc.StandardInput.AutoFlush = true;

                outStr = pc.StandardOutput.ReadToEnd();
                int P = outStr.IndexOf(command) + command.Length;
                outStr = outStr.Substring(P, outStr.Length - P);
                pc.WaitForExit();
                pc.Close();
            }

            outStr = outStr.Trim('\r').Trim('\n');
            cmdRes.Result = outStr;
        }
    }

    class CmdRes
    {
        public string Command { get; set; }
        public string Result { get; set; }
    }
}
